package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/jinzhu/copier"
	"goravel/app/models"
	"goravel/app/services"
	"goravel/app/types"
)

type UserController struct {
	DbServer services.DBServer
}

func NewUserController() *UserController {
	return &UserController{
		DbServer: services.NewDBService(),
	}
}

// List 用户列表
// @Summary      用户列表
// @Tags         User
// @Router       /user [get]
func (r *UserController) List(ctx http.Context) http.Response {
	var users []models.User
	var usersResp []types.UserListResp
	query := facades.Orm().Query().OrderBy("id", "desc")
	data, meta, err := r.DbServer.ListPage(ctx, &users, query, usersResp)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).DataPage(data, meta)
}

// Show 用户详情
// @Summary      用户详情
// @Tags         User
// @Router       /user/{id} [get]
func (r *UserController) Show(ctx http.Context) http.Response {
	var user models.User
	id := ctx.Request().RouteInt("id")
	err := facades.Orm().Query().FindOrFail(&user, id)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	var userResp types.UserInfoResp
	err = copier.Copy(&userResp, &user)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).Data(userResp)
}
